<?php

namespace Wap\Controller;

use Think\Controller;
use Think\Model;
use Wap\Service\WechatService;
use Wap\Service\WeixinService;
use Wap\Service\CustomerService;
use User\Model\RedPacketModel;

class RedPacketController extends WapController
{
    public $wxuser;//活动绑定的微信号

    public $red_packet; //--红包雨活动--

    public function __construct()
    {
        parent::__construct();

        $this->handleCriteriaWxuser();
        if (empty($this->wxuser)) {
            header("Content-type: text/html; charset=utf-8");
            die("活动不存在！");
        }
    }

    /*
    *微信公众号信息
    */
    private function handleCriteriaWxuser()
    {
        $id = I('get.', '', '') ? I("get.id", -1, "") : I("post.id", -1, "");
        if (!empty($id)) {
            $cond_redpacket['id'] = $id;
            $this->red_packet = M("redpacket")->where($cond_redpacket)->find();
            if (empty($this->red_packet)) {
                return false;
            }
            $this->assign('share_able', $this->red_packet['share_able']);
            $this->wxuser = session('redpacket_wxuser_' . $id);
            if (!empty($this->wxuser)) {
                $this->wxuser = session('redpacket_wxuser_' . $id);
                return true;
            }
            $this->wxuser = WeixinService::getWxuser($this->red_packet['token']);
            if (empty($this->wxuser)) {
                return false;
            }
            session('redpacket_wxuser_' . $id, $this->wxuser);
            return true;
        } else {
            return false;
        }
    }

    public function index()
    {
        $id = I("get.id", -1, "");
        $openid = session('session_openid_' . $id);
        if (!empty($openid)) {
            $name = "红包雨";
            $red_packet = $this->red_packet;
            if (!empty($red_packet)) {
                $name = $red_packet['title'];
            }

            $this->assign('name', $name);
            return $this->display('index');
        } else {
            $wechat = new WechatService($this->wxuser['appid'], $this->wxuser['appsecret']);
            $url = $wechat->buildOauthURI("http://" . $_SERVER['HTTP_HOST'] . "/Wap/RedPacket/entry?id=" . $id);
            redirect($url);
        }
    }

    public function entry()
    {
        $code = I("get.code", "", "");
        $id = I("get.id", -1, "");
        $wechat = new WechatService($this->wxuser['appid'], $this->wxuser['appsecret']);
        $openid = $wechat->snsapiBaseUser($code);
        session('session_openid_' . $id, $openid);    //保存session
        if ($openid) {
            $this->isFans($id, $openid);       //判断是否粉丝
        }
        $name = "红包雨";
        $red_packet = $this->red_packet;
        if (!empty($red_packet)) {
            $name = $red_packet['title'];
        }
        $this->assign('name', $name);
        $this->display('index');
    }

    public function redPacket()
    {
        $id = I("get.id", -1, "");
        $name = "红包雨";
        $red_packet = $this->red_packet;
        if (!empty($red_packet)) {
            $name = $red_packet['title'];
        }
        $this->assign('name', $name);
        $this->display('redpacket');
    }

    public function Awards()
    {
        $id = I("get.id", -1, "");
        $name = "红包雨";
        $red_packet = $this->red_packet;
        if (!empty($red_packet)) {
            $name = $red_packet['title'];
        }
        $this->assign('name', $name);
        $this->display('myreward');
    }

    /**
     * 功能：判断活动状态（还未开始、已结束、正常进行）
     * 参数：id
     */
    public function getBgm()
    {
        $bgm = "http://" . $_SERVER['HTTP_HOST'] . '/Public/audio/redpacket/bgm.mp3';
        $hit = "http://" . $_SERVER['HTTP_HOST'] . '/Public/audio/redpacket/hit.wav';
        $lose = "http://" . $_SERVER['HTTP_HOST'] . '/Public/audio/redpacket/lose.wav';
        $win = "http://" . $_SERVER['HTTP_HOST'] . '/Public/audio/redpacket/win.wav';
        $id = I("get.id", -1, "");
        if (empty($id)) {
            $this->ajaxReturn(array(
                'bgm' => $bgm,
                'hit' => $hit,
                'lose' => $lose,
                'win' => $win));
        }
        $cond['status'] = RedPacketModel::STATUS_ACTIVE;
        $cond['redpacket_id'] = $id;
        $redpacket_upload = M("redpacket_upload")->where($cond)->find();
        if (empty($redpacket_upload) || empty($redpacket_upload['bgm'])) {
            $this->ajaxReturn(array(
                'bgm' => $bgm,
                'hit' => $hit,
                'lose' => $lose,
                'win' => $win));
        }
        $bgm = $redpacket_upload['bgm'];
        $this->ajaxReturn(array(
            'bgm' => $bgm,
            'hit' => $hit,
            'lose' => $lose,
            'win' => $win));
    }

    public function getInfo()
    {
        $id = I("get.id", -1, "");
        $again = I("get.again", 0, "");
        $red_packet = $this->red_packet;
        if (empty($red_packet)) {
            $cond['id'] = $id;
            $red_packet = M("redpacket")->where($cond)->find();
        }

        if (empty($red_packet)) {
            return $this->ajaxreturn_getinfo(-1, "已结束", '');
        }
        //--临时字段--
        if ($again == 1) {
            if (!empty($red_packet['reserve'])) {
                $reserve = json_decode($red_packet['reserve'], true);
                if (!empty($reserve['again_url'])) {
                    return $this->ajaxreturn_getinfo(-4, "机会用完!", $reserve['again_url']);
                }
            }
        }
        //----
        $open_id = session('session_openid_' . $id);
        if (empty($open_id)) {
            return $this->ajaxreturn_getinfo(-1, "已结束", $red_packet['info']);
        }
        if ($red_packet['status'] != RedPacketModel::STATUS_ACTIVE) {
            return $this->ajaxreturn_getinfo(-1, "已结束", $red_packet['info']);
        }
        $date = date("Y-m-d H:i:s");
        if ($red_packet['startdate'] > $date) {
            return $this->ajaxreturn_getinfo(-2, "未开始", $red_packet['info']);
        }
        if ($red_packet['enddate'] < $date) {
            return $this->ajaxreturn_getinfo(-1, "已结束", $red_packet['info']);
        }
        if ($red_packet['per_num'] == -1) {
            return $this->ajaxreturn_getinfo(1, "正常", $red_packet['info']);
        }
        $cond_fans['openid'] = $open_id;
        $cond_fans['status'] = RedPacketModel::STATUS_ACTIVE;
        $cond_fans['pid'] = $id;
        $valid_start = date("Y-m-d") . " 00:00:00";
        $valid_end = date("Y-m-d") . " 23:59:59";
        $cond_fans['createdate'] = array("between", array($valid_start, $valid_end));
        $times = M("redpacket_fansaward")->where($cond_fans)->count();
        if ($times < $red_packet['per_num']) {
            return $this->ajaxreturn_getinfo(1, "正常", $red_packet['info']);
        }
        $cond_share['token'] = $red_packet['token'];
        $cond_share['openid'] = $open_id;
        $cond_share['url'] = "http://" . $_SERVER['HTTP_HOST'] .
            '/Wap/RedPacket/index?id=' . $red_packet['id'];
        $cond_share['createdate'] = array("between", array($valid_start, $valid_end));
        $is_share = M("wechat_share")->where($cond_share)->count();
        if ($is_share == 0) {
            return $this->ajaxreturn_getinfo(-3, "机会用完", $red_packet['info']);
        }
        if ($times >= ($red_packet['per_num'] + $red_packet['share_play'])) {
            return $this->ajaxreturn_getinfo(-3, "机会用完!", $red_packet['info']);
        }
        return $this->ajaxreturn_getinfo(1, "正常", $red_packet['info']);
    }

    private function ajaxreturn_getinfo($status = -1, $result = '', $desc = '')
    {
        $this->ajaxReturn(array(
            'status' => $status,
            'result' => $result,
            'desc' => $desc));
    }

    /**
     * 功能：判断是否是粉丝，否则注册粉丝信息
     * 参数：id，token
     */
    private function isFans($id, $openid)
    {
        $red_packet = $this->red_packet;
        if (empty($red_packet)) {
            $red_packet = M("redpacket")->where(['id' => $id])->find();
        }
        if (!empty($red_packet)) {
            $condition['pid'] = $id;
            $condition['token'] = $red_packet['token'];
            $condition['openid'] = $openid;
            $condition['status'] = RedPacketModel::STATUS_ACTIVE;
            $fans = M('redpacket_fans')->where($condition)->find();
            if (empty($fans)) {
                $new_fans = array(
                    'token' => $red_packet['token'],
                    'pid' => $id,
                    'openid' => $openid,
                    'createdate' => date('Y-m-d H:i:s')
                );
                M('redpacket_fans')->add($new_fans);
            }
        }
    }

    public function getRedPackets()
    {
        $redpacket_rate = 0.65;
        $is_luck = 0;
        $delay = 0;
        $slow = 0.2;
        $fast = 3;
        $id = I("get.id", -1, "");
        $red_packet = $this->red_packet;
        $openid = session('session_openid_' . $id);
        if (empty($red_packet) || empty($openid)) {
            $cond['id'] = $id;
            $red_packet = M("redpacket")->where($cond)->find();
        }
        if (empty($red_packet)) {
            return $this->ajaxreturn_getRedPackets();
        }
        //--使用临时字段--
        if (!empty($red_packet['reserve'])) {
            $reserve = json_decode($red_packet['reserve'], true);
            if (!empty($reserve['start_speed'])) {
                $slow = $reserve['start_speed'];
            }
            if (!empty($reserve['end_speed'])) {
                $fast = $reserve['end_speed'];
            }
            if (!empty($reserve['redpacket_rate'])) {
                $redpacket_rate = $reserve['redpacket_rate'];
            }
        }

        $game_time = $red_packet['game_time'];
        if ($game_time <= 5) {
            $delay = 0;
        } elseif ($game_time <= 10 && $game_time > 5) {
            $delay = rand(0, 10);
        } else {
            $delay = rand(10, $game_time);
        }
        $cond_item['redpacket_id'] = $id;
        $cond_item['status'] = RedPacketModel::STATUS_ACTIVE;
        $redpacket_items = M("redpacket_item")->where($cond_item)->order("level desc")->select();
        if (empty($redpacket_items)) {
            return $this->ajaxreturn_getRedPackets($redpacket_rate, $is_luck, $delay, $game_time, $slow, $fast);
        }

        //--判断是否还有玩的机会--
        if ($red_packet['status'] != RedPacketModel::STATUS_ACTIVE) {
            return $this->ajaxreturn_getRedPackets($redpacket_rate, $is_luck, $delay, $game_time, $slow, $fast);
        }
        $date = date("Y-m-d H:i:s");
        if ($red_packet['startdate'] > $date) {
            return $this->ajaxreturn_getRedPackets($redpacket_rate, $is_luck, $delay, $game_time, $slow, $fast);
        }
        if ($red_packet['enddate'] < $date) {
            return $this->ajaxreturn_getRedPackets($redpacket_rate, $is_luck, $delay, $game_time, $slow, $fast);
        }
        $cond_fans['openid'] = $openid;
        $cond_fans['status'] = RedPacketModel::STATUS_ACTIVE;
        $cond_fans['pid'] = $id;
        $valid_start = date("Y-m-d") . " 00:00:00";
        $valid_end = date("Y-m-d") . " 23:59:59";
        $cond_fans['createdate'] = array("between", array($valid_start, $valid_end));
        $times = M("redpacket_fansaward")->where($cond_fans)->count();

        $cond_share['token'] = $red_packet['token'];
        $cond_share['openid'] = $openid;
        $cond_share['url'] = "http://" . $_SERVER['HTTP_HOST'] .
            '/Wap/RedPacket/index?id=' . $red_packet['id'];
        $cond_share['createdate'] = array("between", array($valid_start, $valid_end));
        $is_share = M("wechat_share")->where($cond_share)->count();
        if (($red_packet['per_num'] != -1) && ($times >= $red_packet['per_num']) && $is_share == 0) {
            return $this->ajaxreturn_getRedPackets($redpacket_rate, $is_luck, $delay, $game_time, $slow, $fast);
        }
        if (($red_packet['per_num'] != -1) && ($times >= ($red_packet['per_num'] + $red_packet['share_play']))) {
            return $this->ajaxreturn_getRedPackets($redpacket_rate, $is_luck, $delay, $game_time, $slow, $fast);
        }

        $cond_red_fans['status'] = RedPacketModel::STATUS_ACTIVE;
        $cond_red_fans['pid'] = $id;
        $cond_red_fans['zhongjiang'] = RedPacketModel::STATUS_ACTIVE;
        $cond_red_fans['createdate'] = array("between", array($valid_start, $valid_end));
        $red_award_times = M("redpacket_fansaward")->where($cond_red_fans)->count();
        if (($red_packet['number_limits'] != -1) && $red_award_times >= $red_packet['number_limits']) {
            return $this->ajaxreturn_getRedPackets($redpacket_rate, $is_luck, $delay, $game_time, $slow, $fast);
        }

        //--判断是否中奖--
        foreach ($redpacket_items as $item) {
            if ($item['reserve'] <= 0) {
                continue;
            }
            $range = $item['reserve'] * 100000;
            $random = rand(1, 10000000);
            if ($random <= $range) {
                $cond_award_total['award_id'] = $item['id'];
                $cond_award_total['status'] = RedPacketModel::STATUS_ACTIVE;
                $cond_award_total['pid'] = $red_packet['id'];
                $item_award = M("redpacket_fansaward")->where($cond_award_total)->count();
                $awarded = S("redpacket_award_id" . $item['id']);
                if (($item_award + $awarded) >= $item['number']) {
                    continue;
                }
                $cond_award_person['award_id'] = $item['id'];
                $cond_award_person['status'] = RedPacketModel::STATUS_ACTIVE;
                $cond_award_person['pid'] = $red_packet['id'];
                $cond_award_person['openid'] = $openid;
                $item_award = M("redpacket_fansaward")->where($cond_award_person)->count();
                if ($item_award >= $red_packet['per_num_sum']) {
                    continue;
                }
                $is_luck = 1;
                session('redpacket_' . $id . $openid, $item);
                S("redpacket_award_id" . $item['id'], $awarded + 1, 10);
                break;
            }
        }
        return $this->ajaxreturn_getRedPackets($redpacket_rate, $is_luck, $delay, $game_time, $slow, $fast);
    }

    private function ajaxreturn_getRedPackets($redpacket_rate = 0.65, $is_luck = 0, $delay = 0, $game_time = 30, $slow = 0.5, $fast = 4)
    {
        $this->ajaxReturn(array(
            'redpacket_rate' => $redpacket_rate,
            'is_luck' => $is_luck,
            'delay' => $delay,
            'game_time' => $game_time,
            'slow' => $slow,
            'fast' => $fast
        ));
    }

    /**
     * 功能：我的获奖物品
     * 参数：id
     */
    public function getAward()
    {
        $id = I("get.id", -1, "");
        if (!$id || $id == '-1') {
            $this->ajaxReturn(array('status' => -1, 'result' => '未传入参数id'));
        }
        $openid = session('session_openid_' . $id);
        $condition['pid'] = $id;
        $condition['openid'] = $openid;
        $condition['zhongjiang'] = RedPacketModel::ZHONGJIANG_ACTIVE;
        $condition['status'] = RedPacketModel::STATUS_ACTIVE;
        $fansaward = M("redpacket_fansaward")->where($condition)->order('createdate desc')->select();
        $data = array();
        $awardid = array();
        $newData = array();
        if (!empty($fansaward)) {
            foreach ($fansaward as $value) {
                $data[] = array(
                    'award_id' => $value['award_id'],
                    'createdate' => $value['createdate'],
                    'award_name' => '',
                    'award_level' => '',
                    'award_pic' => ''
                );
                $awardid[] = $value['award_id'];
            }
            $items_where['id'] = array('IN', $awardid);
            $items_where['status'] = RedPacketModel::STATUS_ACTIVE;
            $items = M('redpacket_item')->where($items_where)->select();
            foreach ($items as $item) {
                $award[$item['id']]['award_name'] = $item['name'];
                $award[$item['id']]['award_level'] = RedPacketModel::getLevel($item['level']);
                $award[$item['id']]['award_pic'] = C('SITE_URL') . '/' . $item['pic'];
                $award[$item['id']]['award_attribute'] = !empty($item['attribute']) ? unserialize($item['attribute']) : array();
            }
            foreach ($data as $data_key => $data_value) {
                $data_value['award_name'] = $award[$data_value['award_id']]['award_name'];
                $data_value['award_level'] = $award[$data_value['award_id']]['award_level'];
                $data_value['award_pic'] = $award[$data_value['award_id']]['award_pic'];
                $newData[$data_key][] = array('name' => '奖品', 'value' => $award[$data_value['award_id']]['award_name']);
                $newData[$data_key][] = array('name' => '等级', 'value' => $award[$data_value['award_id']]['award_level']);
                $newData[$data_key][] = array('name' => 'award_pic', 'value' => $award[$data_value['award_id']]['award_pic']);
                if (!empty($award[$data_value['award_id']]['award_attribute'])) {
                    foreach ($award[$data_value['award_id']]['award_attribute'] as $key => $val) {
                        $newData[$data_key][] = array('name' => $key, 'value' => $val);
                    }
                }
                $newData[$data_key][] = array('name' => '中奖时间', 'value' => $data_value['createdate']);
            }
        }
        $this->ajaxReturn(array('status' => 1, 'data' => $newData));
    }


    /**
     *  功能：获取验证码
     */
    public function getVerify()
    {
        $verify = new \Think\Verify();
        $verify->entry();
    }

    /**
     * 功能：完善资料（填写姓名、联系电话）
     * 参数：id,name,phone,verify
     */
    public function setUserinfo()
    {
        $id = I("post.id", -1, "");
        $name = I("post.name", "", "");
        $phone = I("post.phone", "", "");
        $code = I("post.verify", "", "");
        if (!$id || $id == '-1') {
            $this->ajaxReturn(array('status' => -1, 'result' => '未传入参数id'));
        }
        if (!$name || $name == '') {
            $this->ajaxReturn(array('status' => -3, 'result' => '姓名不能为空'));
        }
        if (!$phone || $phone == '') {
            $this->ajaxReturn(array('status' => -4, 'result' => '联系电话不能为空'));
        }
        if (!$code || $code == '') {
            $this->ajaxReturn(array('status' => -5, 'result' => '验证码不能为空'));
        }
        // 检测输入的验证码是否正确
        $verify = new \Think\Verify();
        if (!$verify->check($code, '')) {
            $this->ajaxReturn(array('status' => -6, 'result' => '验证码不正确'));
        }
        $openid = session('session_openid_' . $id);
        $where_fans['pid'] = $id;
        $where_fans['openid'] = $openid;
        $data = array('name' => $name, 'phone' => $phone);
        M('redpacket_fans')->where($where_fans)->save($data);
        $this->ajaxReturn(array('status' => 1, 'result' => '信息保存成功'));
    }

    /**
     * 功能：提供微信分享信息
     * 参数：id
     */
    public function getShareData()
    {
        $id = I("get.id", -1, "");
        $url = I("get.url", "", "");
        if (!$id || $id == '-1') {
            $this->ajaxReturn(array('status' => -1, 'result' => '未传入参数id'));
        }
        $time = date('Y-m-d H:i:s');
        $condition['id'] = $id;
        $condition['startdate'] = array('LT', $time);
        $condition['enddate'] = array('GT', $time);
        $condition['status'] = RedPacketModel::STATUS_ACTIVE;
        $red_packet = M("redpacket")->where($condition)->find();
        if (!empty($red_packet)) {
            $this->wxuser = WeixinService::getWxuser($red_packet['token']);
            $wxJSApi = WeixinService::buildWXJSApi($this->wxuser, $url);
            if (!empty($wxJSApi)) {
                $data = array(
                    'appId' => $this->wxuser['appid'],
                    'nonceStr' => $wxJSApi['noncestr'],
                    'wxTicket' => $wxJSApi['ticket'],
                    'timestamp' => $wxJSApi['timestamp'],
                    'wxSha1' => $wxJSApi['sha1']
                );
                //分享设置
                $data['title'] = $red_packet['share_title'] ? $red_packet['share_title'] : '一起来抢红包雨';
                $data['desc'] = $red_packet['share_desc'] ? $red_packet['share_desc'] : '好多惊喜大奖正在来袭！';
                $data['link'] = $red_packet['share_link'] ? $red_packet['share_link'] : C('SITE_URL') . '/Wap/RedPacket/index?id=' . $id;
                $data['imgUrl'] = $red_packet['share_img'] ? C('SITE_URL') . '/' . $red_packet['share_img'] : C('SITE_URL') . '/Public/images/RedPacket/redpacket/img_share.png';

                $this->ajaxReturn(array('status' => 1, 'result' => '获取分享信息成功', 'data' => $data));
            } else {
                $this->ajaxReturn(array('status' => -2, 'result' => '获取分享信息失败'));
            }
        }
    }

    //微信分享页面增加红包雨抽奖机会
    public function gameChance()
    {
        $id = I("post.id", -1, "");
        $openid = session('session_openid_' . $id);
        if (!$id || $id == -1) {
            $this->ajaxReturn(array('status' => -1, 'result' => '未获得id，分享获得机会失败'));
        }
        $token = M('redpacket')->where(['id' => $id])->getField("token");
        if (!$token) {
            $this->ajaxReturn(array('status' => -1, 'result' => '未获得token，分享获得机会失败'));
        }
        if (!$openid) {
            $this->ajaxReturn(array('status' => -1, 'result' => '未获得openid，分享获得机会失败'));
        }
        $data = array(
            'token' => $token,
            'openid' => $openid,
            'url' => 'http://' . $_SERVER['HTTP_HOST'] . '/Wap/RedPacket/index?id=' . $id
        );
        $added = M("wechat_share")->add($data);
        if ($added) {
            $this->ajaxReturn(array('status' => 1, 'result' => '额外增加一次抽奖机会成功'));
        } else {
            $this->ajaxReturn(array('status' => 0, 'result' => '额外增加一次抽奖机会失败'));
        }
    }

    public function setAward()
    {
        $params = I("post.", "", "");
        $red_packet = $this->red_packet;
        $openid = session('session_openid_' . $params['id']);
        if (empty($red_packet)) {
            $cond['id'] = $params['id'];
            $red_packet = M("redpacket")->where($cond)->find();
        }
        if (empty($red_packet) || empty($openid)) {
            return $this->ajaxreturn_setAward();
        }
        if ($params['type'] != 1) {
            return $this->ajaxreturn_setAward();
        }
        $item = session('redpacket_' . $params['id'] . $openid);
        if (empty($item)) {
            return $this->ajaxreturn_setAward();
        }
        return $this->ajaxreturn_setAward(1, $item['name'], "http://" . $_SERVER['HTTP_HOST'] . "/" . $item['pic']);
    }

    private function ajaxreturn_setAward($code = 2, $name = '未中奖', $picurl = '', $times = 0)
    {
        $id = I("post.id", -1, '');
        $openid = session('session_openid_' . $id);
        $redpacket = $this->red_packet;
        $return_code = $code;
        if ($code != 1) {
            session('redpacket_' . $id . $openid, null);
            $data['token'] = !empty($redpacket['token']) ? $redpacket['token'] : '';
            $data['pid'] = !empty($redpacket['id']) ? $redpacket['id'] : '';
            $data['award_id'] = 0;
            $data['zhongjiang'] = 9;
            $data['openid'] = $openid;
            M("redpacket_fansaward")->add($data);
        } else {
            $item = session('redpacket_' . $id . $openid);
            session('redpacket_' . $id . $openid, null);

            $redpacket_fansaward = M("redpacket_fansaward");
            $redpacket_fansaward->startTrans();
            $data['token'] = $redpacket['token'];
            $data['pid'] = $redpacket['id'];
            $data['openid'] = $openid;
            $data['zhongjiang'] = 1;
            $data['award_id'] = $item['id'];
            M("redpacket_fansaward")->add($data);

            $cond_red_award['pid'] = $redpacket['id'];
            $cond_red_award['status'] = RedPacketModel::STATUS_ACTIVE;
            $valid_start = date("Y-m-d") . " 00:00:00";
            $valid_end = date("Y-m-d") . " 23:59:59";
            $cond_red_award['zhongjiang'] = RedPacketModel::ZHONGJIANG_ACTIVE;
            $cond_red_award['createdate'] = array("between", array($valid_start, $valid_end));
            $red_award = 0;
            if ($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com') {
                $red_award = M("redpacket_fansaward", 'esm_', 'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')->where($cond_red_award)->count();
            } else {
                $red_award = M("redpacket_fansaward")->where($cond_red_award)->count();
            }

            if (($redpacket['number_limits'] != -1) && ($red_award >= $redpacket['number_limits'])) {
                $return_code = -2;
                $redpacket_fansaward->rollback();
                $this->ajaxReturn(array(
                    'code' => $return_code,
                    'name' => "未中奖！",
                    'picurl' => $picurl,
                    'times' => $times
                ));
            }

            $cond_award_person['status'] = RedPacketModel::STATUS_ACTIVE;
            $cond_award_person['pid'] = $redpacket['id'];
            $cond_award_person['openid'] = $openid;
            $item_award = 0;
            if ($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com') {
                $item_award = M("redpacket_fansaward", 'esm_', 'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')->where($cond_award_person)->count();
            } else {
                $item_award = M("redpacket_fansaward")->where($cond_award_person)->count();
            }
            if ($item_award > $redpacket['per_num_sum']) {
                $return_code = -2;
                $redpacket_fansaward->rollback();
                $this->ajaxReturn(array(
                    'code' => $return_code,
                    'name' => '未中奖！',
                    'picurl' => $picurl,
                    'times' => $times
                ));
            }
            $cond_award_total['award_id'] = $item['id'];
            $cond_award_total['status'] = RedPacketModel::STATUS_ACTIVE;
            $cond_award_total['pid'] = $redpacket['id'];
            if ($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com') {
                $item_award = M("redpacket_fansaward", 'esm_', 'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')->where($cond_award_total)->count();
            } else {
                $item_award = M("redpacket_fansaward")->where($cond_award_total)->count();
            }
            if ($item_award >= $item['number']) {
                $return_code = -1;
                $redpacket_fansaward->rollback();
                $this->ajaxReturn(array(
                    'code' => $return_code,
                    'name' => '未中奖',
                    'picurl' => $picurl,
                    'times' => $times
                ));
            }
            $redpacket_fansaward->commit();
        }
        $this->ajaxReturn(array(
            'code' => $return_code,
            'name' => $name,
            'picurl' => $picurl,
            'times' => $times
        ));
    }

    public function getName()
    {
        $id = I("get.id", -1, '');
        $red_packet = $this->red_packet;
        if (empty($red_packet)) {
            $cond['id'] = $id;
            $red_packet = M("redpacket")->where($cond)->find();
        }
        $name = "红包雨";
        if (!empty($red_packet)) {
            $name = $red_packet['title'];
        }
        $this->ajaxReturn(array(
            'name' => $name
        ));
    }

}